﻿Partial Class App_SocialSEO
    Inherits MyUI.PageBaseApp

    Protected SortGridQuery, SortGridFollStaus As UI.SortControl

    Public CurrAccount As mDB.Account

    Dim FolderParentId As Integer


    <Services.WebMethod()> _
    Public Shared Function AutoCompleteHashTags(ByVal k As String) As String()

        Dim HashTags As Dictionary(Of String, Integer) = HttpContext.Current.Session("HashTags")

        If HashTags Is Nothing Or k.Trim = "" Then
            Return {""}
        End If

        Dim a = HashTags.Where(Function(o) o.Key.Substring(1).StartsWith(k)).OrderByDescending(Function(o) o.Value).Select(Function(o) o.Key).Take(100).ToArray

        Return a

    End Function
#Region "PAGE"
    Protected Sub Page_Load(sender As Object, e As System.EventArgs) Handles Me.Load

        CurrAccount = CurrUser.CurrAccount

        'CphMainContent
        'Content2
        If Not MyApp.DataNet(CurrAccount.Network_Id).App.SocialSeo Then
            FC(Of ContentPlaceHolder)("CphMainContent", Me.Master).Visible = False
            Exit Sub
        End If

        Dim FolderType = mDB.Folder.GetFolderType(mDB.Folder.DataType.QUERY, CurrAccount.Network_Id)
        Me.JsVar("root_folder_id") = CurrUser.Tab_Folder(FolderType, 0).ToObj.Id
        Me.JsVar("tree_type_id") = CInt(FolderType)
        Me.JsVar("webservice_url") = Me.ResolveClientUrl("~/Webservice/Folder.asmx/")
        Me.JsVar("icons_path") = Me.ResolveClientUrl("~/Style/App/img/Icons/")

        ScriptManager.GetCurrent(Page).EnablePageMethods = True

        FolderParentId = Utils.Conv.ToInt(Me.HidSelectFolderId.Value) ' Me.HidSelectFolderId.Value

        SortGridQuery = New UI.SortControl(Me.ListQuery.ID, Me.ViewState, "Query", SortDirection.Ascending)

        'SortGridLocations = New UI.SortControl(Me.GridElaborations.ID, Me.ViewState, "Query", SortDirection.Ascending)


        If Not Me.IsPostBack Then
            SetDataPage()
        Else

        End If



    End Sub
    Public Sub SetDataPage()




    End Sub
#End Region


#Region "WIZARD"

    Protected Sub BtnWizAddFollQuery_Click(sender As Object, e As EventArgs) Handles BtnWizAddQuery.Click

        AddQuery(Me.TxtWiz1Query1.Text)
        AddQuery(Me.TxtWiz1Query2.Text)
        AddQuery(Me.TxtWiz1Query3.Text)
        AddQuery(Me.TxtWiz1Query4.Text)

        Me.PnlWizFinish.Visible = True
        Me.PnlWiz1.Visible = False

        Me.SetListEnquiry()

    End Sub

    Private Sub AddQuery(q As String)

        If q <> "#" Then

            If Not MyApp.GetUserLimitPlan(GloukDB.Plan.LimitType.AUTO_FOLLOWER_PER_ACCOUNT, True, CurrAccount.Id) Then

                Dim Query = (New mDB.Query With {.Folder_Id = Me.FolderParentId, .Query = q, .Network_Id = CurrAccount.Network_Id}).SetDefault

                DB.TAB.Query.InsertOnSubmit(Query)
                DB.SubmitChanges()

            End If

        End If

    End Sub

#End Region

#Region "ENQUIRY"

    Public Sub SetListEnquiry()

        SetListQuery()
        SetListProfile(False)

        Me.UpPEnquiry.Update()

    End Sub


    Public Sub SetListQuery()

        Me.SetListQuery(False)

    End Sub
    Public Sub SetListQuery(AddRow As Boolean)

        Me.SetListQuery(AddRow, New mDB.Query)

    End Sub
    Public Sub SetListQuery(AddRow As Boolean, QueryDef As mDB.Query)
        Dim list = Me.ListQuery

        Dim dt = SortGridQuery.SortQuery(CurrUser.View_Query(FolderParentId).SetSelect("query.*")).ToList  '

        If AddRow Then
            'Utils.DT.AddDataRowAt(qs, UI.Grid.GetIndexDataFromRow(g, 0))
            dt.Insert(UI.ListData.GetIndexData(list, 0), QueryDef)
            list.EditIndex = 0
        End If

        'query che segui l'utente

        '-------------------------------------------------------
        ' LAYOUT
        '-------------------------------------------------------

        Dim DataBind = UI.ListData.Bind(list, dt, {"id"})


        Dim QueryFoll = CurrAccount.Tab_Auto_Follow_Query.ToDictionary(Of Integer)("query_id")
        Dim QueryListen = CurrAccount.Tab_Listen_Query.ToDictionary(Of Integer)("query_id")

        For Each gr In list.Items
            'Dim Data = DirectCast(DataBind(UI.ListDataItem.GetIndexData(gr)), mDB.Query)
            Dim Data As mDB.Query = DataBind(UI.ListDataItem.GetIndexData(gr))

            MyUI.Data.SetRowStatusQuery(gr, Data)

            If gr.DisplayIndex <> list.EditIndex Then

                Dim BtnDownloadQuery = UI.ListDataItem.GetControl(Of LinkButton)(gr, "BtnDownloadQuery")
                Dim BtnLoadQuery = UI.ListDataItem.GetControl(Of LinkButton)(gr, "BtnLoadQuery")
                Dim BtnEditRow = UI.ListDataItem.GetControl(Of LinkButton)(gr, "BtnEditRow")

                BtnLoadQuery.Enabled = Data.DataStatus <> mDB.Query.DataStausType.EMPTY
                BtnDownloadQuery.Enabled = Data.Id <> 0
                'UI.Controls.ClassSet(BtnDownloadQuery, BtnDownloadQuery.Enabled, "a-icona-freccia-h", "a-icona-freccia")

                '
                'UI.Controls.ClassSet(BtnAddAutoFollQuery, QueryFoll.ContainsKey(Data.Id), "a-icona-mano-h", "a-icona-mano")
                'UI.Controls.ClassSet(BtnAddListenQuery, QueryListen.ContainsKey(Data.Id), "a-icona-canc-v", "a-icona-canc")

                If Data.Last_Update = Date.MinValue Then
                    BtnEditRow.Enabled = True
                Else
                    BtnEditRow.Enabled = False
                    UI.Controls.ClassReplace(BtnEditRow, "a-icona-matita", "en-vuoto")
                End If


            End If

        Next



    End Sub

    Protected Sub BtnAddQuery_Click(sender As Object, e As System.EventArgs) Handles BtnAddQuery.Click

        If Not MyApp.GetUserLimitPlan(GloukDB.Plan.LimitType.QUERY_PER_USER, True) Then
            SetListQuery(True)
        End If

    End Sub
    Protected Sub BtnAddProfile_Click(sender As Object, e As System.EventArgs) Handles BtnAddProfile.Click

        If Not MyApp.GetUserLimitPlan(GloukDB.Plan.LimitType.QUERY_PER_USER, True) Then
            SetListProfile(True)
        End If

    End Sub

    Public Sub SetListProfile()

        SetListProfile(False)

    End Sub


    Public Sub SetListProfile(AddRow As Boolean)
        Dim list = Me.ListProfile

        Dim q = CurrUser.Tab_Profile(FolderParentId).
            REL.Profile.Account.REL.Account.Account_Add_Info

        Dim dt = q.ToDataTable

        If AddRow Then
            Utils.DT.AddDataRowAt(dt, UI.ListData.GetIndexData(list, 0))
            list.EditIndex = 0
        End If

        Dim Profiles = q.ToList

        'query che segui l'utente
        Dim ProfileFoll = CurrAccount.Tab_Auto_Follow_Profile.ToDictionary(Of Integer)("profile_account_id")

        '-------------------------------------------------------
        ' LAYOUT
        '-------------------------------------------------------

        Dim DataBind = UI.ListData.Bind(list, dt, {"id"})

        For Each gr In list.Items
            Dim Data = Utils.DT.ToObj(Of mDB.Profile)(DataBind(UI.ListDataItem.GetIndexData(gr)))

            If gr.DisplayIndex <> list.EditIndex Then

                Dim BtnDownloadQuery = UI.ListDataItem.GetControl(Of LinkButton)(gr, "BtnDownloadQuery")
                Dim BtnLoadQuery = UI.ListDataItem.GetControl(Of LinkButton)(gr, "BtnLoadQuery")

                BtnLoadQuery.Enabled = Data.DataStatus <> mDB.Query.DataStausType.EMPTY
                BtnDownloadQuery.Enabled = Data.Id <> 0

                MyUI.Data.SetRowStatusProfile(gr, Data)

            End If

        Next

    End Sub
    Protected Sub BtnReload_UpPEnquiry_Click(sender As Object, e As System.EventArgs) Handles BtnReload_UpPEnquiry.Click

        SetListEnquiry()

    End Sub


    Protected Sub ListQuery_ItemCommand(sender As Object, e As ListViewCommandEventArgs) Handles ListQuery.ItemCommand
        Dim list As ListView = sender

        Dim id = UI.ListDataItem.GetKey(e.CommandSource)

        If id Is Nothing Then
            Exit Sub
        End If

        Dim Row = UI.ListDataItem.GetRow(e.CommandSource)

        Dim query = DB.TAB.Query.GetByPK(id)

        Select Case e.CommandName

            Case "CANCEL_ROW_EDIT"

                list.EditIndex = -1
                SetListQuery(False)

            Case "UPDATE_ROW"

                If query Is Nothing Then
                    query = (New mDB.Query With {.Folder_Id = Me.FolderParentId}).SetDefault
                    DB.TAB.Query.InsertOnSubmit(query)
                End If

                query.Query = UI.ListDataItem.GetTextBox(Row, "TxtQuery").Text
                query.Place = UI.ListDataItem.GetTextBox(Row, "TxtPlace").Text
                query.Lang_Code = UI.ListDataItem.GetTextBox(Row, "TxtLangCode").Text
                'query.Description = UI.ListDataItem.GetTextBox(gr, "TxtDescription").Text
                query.Network_Id = CurrAccount.Network_Id

                DB.SubmitChanges()

                list.EditIndex = -1
                SetListQuery(False)

            Case "EDIT_ROW"
                list.EditIndex = Row.DisplayIndex
                SetListQuery(False)

            Case "DELETE_ROW"
                DB.TAB.Query.DeleteOnSubmit(query)
                DB.SubmitChanges()
                SetListQuery(False)


            Case "LOAD"

                SetDataSearchQuery(New List(Of mDB.Query) From {query}, "")

            Case "DOWNLOAD"
                query.ReIndex()
                DB.SubmitChanges()
                SetListQuery(False)


        End Select
    End Sub
    Protected Sub ListProfile_ItemCommand(sender As Object, e As ListViewCommandEventArgs) Handles ListProfile.ItemCommand
        Dim List As ListView = sender
        Dim id = UI.ListDataItem.GetKey(e.CommandSource)
        If id Is Nothing Then
            Exit Sub
        End If
        Dim Row = UI.ListDataItem.GetRow(e.CommandSource)

        Dim Profile = DB.TAB.Profile.GetByPK(id)

        Select Case e.CommandName


            Case "CANCEL_ROW_EDIT"

                List.EditIndex = -1
                SetListProfile(False)

            Case "UPDATE_ROW"


                Dim tw = New MyApp.Network.Twitter(CurrAccount.GetOauth)
                Dim Txtusername = UI.ListDataItem.GetTextBox(Row, "Txtusername")

                Dim AccToAdd As New List(Of String)
                AccToAdd.Add(Txtusername.Text.Replace("@", ""))


                Dim Accs = tw.DownloadAccounts(AccToAdd, Nothing)

                If Accs.Count > 0 Then
                    Dim Prof = New mDB.Profile With {
                        .Folder_Id = FolderParentId, .Account_Id = Accs(0).Id, .Post_Download_Count = -1
                    }

                    DB.TAB.Profile.InsertOnSubmit(Prof)
                    'CurrTask.Share_Account_Id = Accs(0).Id
                    'CurrTask.Share_Account_Username = Me.TxtShareAccountUsername.Text
                    DB.SubmitChanges()

                End If


                List.EditIndex = -1
                SetListProfile(False)

            Case "EDIT_ROW"
                List.EditIndex = Row.DisplayIndex
                SetListProfile(False)

            Case "DELETE_ROW"

                DB.TAB.Profile.DeleteOnSubmit(Profile)
                DB.SubmitChanges()
                SetListProfile(False)

            Case "LOAD"

                SetDataSearchProfile(New List(Of mDB.Profile) From {Profile}, "")
                Me.UpPQueryResult.Update()

            Case "DOWNLOAD"
                Profile.ReIndex()
                DB.SubmitChanges()
                SetListProfile(False)



        End Select
    End Sub

#End Region

#Region "ANALISYS"

    Public Sub SetDataSearchQuery(qs As List(Of mDB.Query), key As String)


        Dim arcs As New List(Of mDB.Archive_Simil_Text)
        For Each q In qs

            arcs.Add(mDB.Archive_Simil_Text.GetArchive(mDB.Archive_Simil_Text.ArchiveType.POST_QUERY, q.Id))

        Next

        Me.SetListCloud(arcs, key)

        If qs.Count = 1 Then

            Dim DtImage = qs(0)._Tab_Query_Post.
                Where("image_url", "<>", "").
                OrderBy("share_count desc", "account_follower_count desc").
                GroupBy("image_url").
                SetSelect("image_url").
                Limit(24).
            ToDataTable()

            Me.RptImages.DataSource = DtImage
            Me.RptImages.DataBind()
            Me.UpPImageResult.Update()
        End If

    End Sub
    Public Sub SetDataSearchProfile(qs As List(Of mDB.Profile), key As String)


        Dim arcs As New List(Of mDB.Archive_Simil_Text)
        For Each q In qs

            arcs.Add(mDB.Archive_Simil_Text.GetArchive(mDB.Archive_Simil_Text.ArchiveType.POST_ACCOUNT, q.Id))

        Next

        Me.SetListCloud(arcs, key)


    End Sub

    Protected Sub Btncerca_Click(sender As Object, e As System.EventArgs) Handles Btncerca.Click

        Dim q = CurrUser.View_Query(FolderParentId).SetSelect("query.*").ToList()  '       New List(Of mDB.Query) From {DB.TAB.Query.GetByPK(22), DB.TAB.Query.GetByPK(25)}

        Me.SetDataSearchQuery(q, Me.Txtpost.Text)

    End Sub
    Protected Sub BtnAnalizePost_Click(sender As Object, e As System.EventArgs) Handles BtnAnalizePost.Click, BtnAnalizePostFolder.Click

        Dim q = CurrUser.View_Query(FolderParentId).SetSelect("query.*").ToList  '       New List(Of mDB.Query) From {DB.TAB.Query.GetByPK(22), DB.TAB.Query.GetByPK(25)}

        Me.SetDataSearchQuery(q, Me.CtrPostSend.PostText)

    End Sub

    'Protected Sub RptHasttag_ItemCommand(source As Object, e As System.Web.UI.WebControls.RepeaterCommandEventArgs) Handles RptHasttag.ItemCommand, RptWord.ItemCommand

    '    Select Case e.CommandName.ToUpper
    '        Case "ADD_WORD"
    '            Me.Txtpost.Text &= " " & e.CommandArgument

    '        Case "ADD_QUERY"
    '            SetListQuery(True, New mDB.Query With {.Query = e.CommandArgument})
    '            'Me.UpPElaborations.Update()
    '            'Me.Txtpost.Text &= " " & e.CommandArgument

    '        Case "VIEW_POST"

    '            SetListPostQuery(e.CommandArgument)

    '    End Select

    'End Sub
#End Region

#Region "CLOUD"

    Public Sub SetListCloud(qs As List(Of mDB.Archive_Simil_Text), key As String)

        'Dim results As New List(Of SimilText.MatchResult)
        'Dim wids As New Dictionary(Of String, Integer)
        Dim HashTags As New Dictionary(Of String, Integer)
        Dim HashTags2index As New Dictionary(Of String, Integer)
        Dim HashTags2 As New Dictionary(Of String, Integer)

        Dim Words As New Dictionary(Of String, Integer)
        Dim TotTempo As Double = 0
        'Dim DicDer As New SimilText.Dictionary

        key = key.Trim

        '----------------------------------------
        ' RICERCA
        '----------------------------------------------------------

        Dim t = Now.Ticks

        Dim AD As SimilText.ArchiveData

        For Each q In qs

            'Dim AD = mDB.Archive_Simil_Text.GetArchive(mDB.Archive_Simil_Text.ArchiveType.POST_QUERY, q.Id).GetSimilTextArchiveData
            AD = q.GetSimilTextArchiveData

            Dim f As New SimilText.FindSimilarText(AD)

            f.Text = key
            f.RankMin = IIf(key = "", 0, 1)
            f.Find()
            f.Close()

            'results.AddRange(f.Result.Matches.Take(100).ToList)

            TotTempo += f.Result.ExecTime

            '----------------------------------------------------------
            'trova le parole + utilizzate
            For Each r In f.Result.HashTagCluster1
                Dim w = AD.Dictionary.WordsList(r.Key).Word
                If HashTags.ContainsKey(w) Then
                    HashTags(w) += r.Value
                Else
                    HashTags.Add(w, r.Value)
                End If
            Next

            For Each r In f.Result.HashTagCluster2
                Dim h = r.Key.Split("_")
                Dim w1 = AD.Dictionary.WordsList(h(0)).Word
                Dim w2 = AD.Dictionary.WordsList(h(1)).Word
                Dim keyhast = w1 & "&&" & w2

                If HashTags2.ContainsKey(keyhast) Then
                    HashTags2(keyhast) += r.Value
                Else
                    HashTags2.Add(keyhast, r.Value)
                End If
                If Not HashTags2index.ContainsKey(w1) Then
                    HashTags2index.Add(w1, 0)
                End If
                If Not HashTags2index.ContainsKey(w2) Then
                    HashTags2index.Add(w2, 0)
                End If
                HashTags2index(w1) += 1
                HashTags2index(w2) += 1

            Next


            For Each r In f.Result.WordCluster1
                Dim w = AD.Dictionary.WordsList(r.Key).Word
                If Words.ContainsKey(w) Then
                    Words(w) += r.Value
                Else
                    Words.Add(w, r.Value)
                End If
            Next

            'DicDer = AD.Stemming
        Next

        Session("HashTags") = HashTags

        TotTempo = (Now.Ticks - t) / 10000000

        'Me.LblExec.Text = String.Format("Analisi effettuata in {0} sec.", TotTempo)

        '----------------------------------------
        ' PRENDE LE PAROLE INSERITE E LE SUE DERIVATE
        '----------------------------------------------------------

        Dim WordSearch As New Dictionary(Of String, Boolean)
        For Each w In SimilText.TextTools.TextToWord(key)
            Dim word = w
            Dim isHashtag = False

            If w.StartsWith("#") Then
                word = w.Substring(1)
                isHashtag = True
            End If
            If Not WordSearch.ContainsKey(word) Then
                WordSearch.Add(word, isHashtag)
            End If

        Next

        Dim WordSearchStemm As New Dictionary(Of String, Boolean)
        For Each w In WordSearch
            If AD.Stemming.Words.ContainsKey(w.Key) Then
                Dim We = AD.Stemming.WordsList(AD.Stemming.Words(w.Key))
                If We IsNot Nothing Then
                    Dim Wordtemp = (From d In We.StemmingIds Select AD.Stemming.WordsList(d).Word).ToList
                    For Each wt In Wordtemp
                        WordSearchStemm.Add(wt, w.Value)
                    Next
                End If
            End If

        Next

        'calcoli per il tagcloud
        Dim HashTagsCloud = HashTags.OrderByDescending(Function(o) o.Value).Take(100).ToList
        Dim WordsCloud = Words.OrderByDescending(Function(o) o.Value).Take(100).ToList

        Dim TotHashtag = HashTags.Sum(Function(o) o.Value)
        Dim TotWord = Words.Sum(Function(o) o.Value)
        Dim TotCloudHashtag = HashTagsCloud.Sum(Function(o) o.Value)
        Dim TotCloudword = WordsCloud.Sum(Function(o) o.Value)

        '----------------------------------------
        ' LAYOUT
        '----------------------------------------

        'hashtag
        'UI.Rep.Bind(Me.RptHasttag, HashTagsCloud)

        Dim DataBind = UI.ListData.Bind(Me.ListHashtag, HashTagsCloud, {})

        Dim TotValue = 1
        For Each gr In Me.ListHashtag.Items
            Dim Data As KeyValuePair(Of String, Integer) = DataBind(UI.ListDataItem.GetIndexData(gr)) ' DirectCast(DataBind(UI.ListDataItem.GetIndexData(gr)), KeyValuePair(Of String, Integer))
            Dim Pan = UI.ListDataItem.GetPanel(gr, "PnlTag")
            Dim Word = Data.Key

            Pan.CssClass = LevelToClass(Utils.Math.LevelFromValue(1, TotCloudHashtag, 4, TotValue))

            TotValue += Data.Value

            Word = Word.Substring(1)
            Me.SetRowStatusHashTag(gr, WordSearch, WordSearchStemm, Word)

        Next

        'word
        'DataBind = UI.Rep.Bind(Me.RptWord, WordsCloud)
        DataBind = UI.ListData.Bind(Me.ListWords, WordsCloud, {})

        For Each gr In Me.ListWords.Items
            Dim Data As KeyValuePair(Of String, Integer) = DataBind(UI.ListDataItem.GetIndexData(gr)) ' DirectCast(DataBind(UI.ListDataItem.GetIndexData(gr)), KeyValuePair(Of String, Integer))
            Dim Word = Data.Key


            Me.SetRowStatusWord(gr, WordSearch, WordSearchStemm, Word)

        Next


        'For ct = 0 To RptWord.Items.Count - 1
        '    Dim d = WordsCloud(UI.Rep.GetIndexData(Me.RptWord, ct))
        '    Dim LinkButton = UI.Rep.GetControl(Of LinkButton)(Me.RptWord, ct, "LnkTag")
        '    Dim Word = d.Key

        '    LinkButton.Text = Word
        '    LinkButton.CommandArgument = Word
        '    LinkButton.ToolTip = UI.Print.Num2(d.Value / TotCloudword * 100) & "% sul cloud - " & UI.Print.Num2(d.Value / TotWord * 100) & "% sul tot"


        '    If WordSearch.ContainsKey(Word) Then
        '        If Not WordSearch(Word) Then
        '            LinkButton.ForeColor = Drawing.Color.Green
        '        Else
        '            LinkButton.ForeColor = Drawing.Color.OrangeRed
        '        End If
        '        LinkButton.Font.Bold = True
        '    Else
        '        If WordStemm.ContainsKey(Word) Then
        '            If Not WordStemm(Word) Then
        '                LinkButton.ForeColor = Drawing.Color.OrangeRed
        '            Else
        '                LinkButton.ForeColor = Drawing.Color.Orange
        '            End If
        '            LinkButton.Font.Bold = True
        '        End If
        '    End If
        'Next

        'Dim TotValue = 1
        'For ct = 0 To RptHasttag.Items.Count - 1
        '    Dim d = HashTagsCloud(UI.Rep.GetIndexData(Me.RptHasttag, ct))
        '    Dim Pan = UI.Rep.GetControl(Of Panel)(Me.RptHasttag, ct, "PnlTag")

        '    'HtmlDivTag
        '    Dim Word = d.Key

        '    Dim Classe = Utils.Math.LevelFromValue(1, TotCloudHashtag, 4, TotValue)
        '    TotValue += d.Value
        '    Pan.CssClass &= " class" & Classe

        '    LinkButton.Font.Size = 16 - (Classe * 2)
        '    LinkButton.Text = Word
        '    LinkButton.CommandArgument = Word
        '    LinkButton.ToolTip = UI.Print.Num2(d.Value / TotCloudHashtag * 100) & "% sul cloud - " & UI.Print.Num2(d.Value / TotHashtag * 100) & "% sul tot"

        '    Word = Word.Substring(1)
        '    If WordSearch.ContainsKey(Word) Then
        '        If WordSearch(Word) Then
        '            LinkButton.ForeColor = Drawing.Color.Green
        '        Else
        '            LinkButton.ForeColor = Drawing.Color.OrangeRed
        '        End If
        '        LinkButton.Font.Bold = True
        '    Else
        '        If WordStemm.ContainsKey(Word) Then
        '            If WordStemm(Word) Then
        '                LinkButton.ForeColor = Drawing.Color.OrangeRed
        '            Else
        '                LinkButton.ForeColor = Drawing.Color.Orange
        '            End If
        '            LinkButton.Font.Bold = True
        '        End If
        '    End If
        'Next

        'word
        'UI.Rep.Bind(Me.RptWord, WordsCloud)
        'For ct = 0 To RptWord.Items.Count - 1
        '    Dim d = WordsCloud(UI.Rep.GetIndexData(Me.RptWord, ct))
        '    Dim LinkButton = UI.Rep.GetControl(Of LinkButton)(Me.RptWord, ct, "LnkTag")
        '    Dim Word = d.Key

        '    LinkButton.Text = Word
        '    LinkButton.CommandArgument = Word
        '    LinkButton.ToolTip = UI.Print.Num2(d.Value / TotCloudword * 100) & "% sul cloud - " & UI.Print.Num2(d.Value / TotWord * 100) & "% sul tot"


        '    If WordSearch.ContainsKey(Word) Then
        '        If Not WordSearch(Word) Then
        '            LinkButton.ForeColor = Drawing.Color.Green
        '        Else
        '            LinkButton.ForeColor = Drawing.Color.OrangeRed
        '        End If
        '        LinkButton.Font.Bold = True
        '    Else
        '        If WordStemm.ContainsKey(Word) Then
        '            If Not WordStemm(Word) Then
        '                LinkButton.ForeColor = Drawing.Color.OrangeRed
        '            Else
        '                LinkButton.ForeColor = Drawing.Color.Orange
        '            End If
        '            LinkButton.Font.Bold = True
        '        End If
        '    End If
        'Next




        Dim nodes As New List(Of Object)
        Dim edges As New List(Of Object)


        Dim HashTagsCloud2 = HashTags2index.OrderByDescending(Function(o) o.Value).Take(50).ToDictionary(Of String, Integer)(Function(o) o.Key, Function(o) o.Value)

        'Dim minValue2 = HashTagsCloud2.Min(Function(o) o.Value)
        'Dim maxValue2 = HashTagsCloud2.Max(Function(o) o.Value)
        Dim maxValue2 = HashTagsCloud2.Sum(Function(o) o.Value)
        Dim TotValue2 = 1
        For Each h In HashTagsCloud2

            Dim lvl = Utils.Math.LevelFromValue(1, maxValue2, 4, TotValue2)

            TotValue2 += h.Value

            nodes.Add(New With {.id = h.Key, .label = h.Key, .title = h.Key, .value = 15 - lvl, .shape = "dot", .group = "level_" & lvl})
        Next
        For Each h In HashTags2
            Dim p = h.Key.Split({"&&"}, StringSplitOptions.RemoveEmptyEntries)
            If HashTagsCloud2.ContainsKey(p(0)) And HashTagsCloud2.ContainsKey(p(1)) Then
                edges.Add(New With {.from = p(0), .to = p(1), .value = h.Value})
            End If
        Next


        Dim json = MyApp.JSONSerialize(New With {
            .nodes = nodes, .edges = edges
        })

        Me.AddJScript(SF("draw({0});", json))











        Me.UpPQueryResult.Update()


    End Sub
    Public Sub SetRowStatusHashTag(gr As Control, WordSearch As Dictionary(Of String, Boolean), WordStemm As Dictionary(Of String, Boolean), word As String)

        Dim LinkButton = UI.ListDataItem.GetLinkButton(gr, "LnkTag")

        If WordSearch.ContainsKey(word) Then
            If WordSearch(word) Then
                LinkButton.ForeColor = Drawing.Color.Green
            Else
                LinkButton.ForeColor = Drawing.Color.OrangeRed
            End If
            LinkButton.Font.Bold = True
        Else
            If WordStemm.ContainsKey(word) Then
                If WordStemm(word) Then
                    LinkButton.ForeColor = Drawing.Color.OrangeRed
                Else
                    LinkButton.ForeColor = Drawing.Color.Orange
                End If
                LinkButton.Font.Bold = True
            End If
        End If
    End Sub
    Public Sub SetRowStatusWord(gr As Control, WordSearch As Dictionary(Of String, Boolean), WordStemm As Dictionary(Of String, Boolean), word As String)

        Dim LinkButton = UI.ListDataItem.GetLinkButton(gr, "LnkTag")

        If WordSearch.ContainsKey(word) Then
            If Not WordSearch(word) Then
                LinkButton.ForeColor = Drawing.Color.Green
            Else
                LinkButton.ForeColor = Drawing.Color.OrangeRed
            End If
            LinkButton.Font.Bold = True
        Else
            If WordStemm.ContainsKey(word) Then
                If Not WordStemm(word) Then
                    LinkButton.ForeColor = Drawing.Color.OrangeRed
                Else
                    LinkButton.ForeColor = Drawing.Color.Orange
                End If
                LinkButton.Font.Bold = True
            End If
        End If
    End Sub
    Private Function LevelToClass(lvl As Integer) As String

        Select Case lvl
            Case 1
                Return "hash-r"
            Case 2
                Return "hash-g"
            Case 3
                Return "hash-v"
            Case Else
                Return "hash-n"



        End Select

    End Function
    Protected Sub ListHashtag_ItemCommand1(sender As Object, e As ListViewCommandEventArgs) Handles ListHashtag.ItemCommand, ListWords.ItemCommand


        Select Case e.CommandName.ToUpper
            Case "ADD_WORD"
                Me.CtrPostSend.PostText &= " " & e.CommandArgument
                Me.UpPComposePost.Update()
            Case "ADD_QUERY"
                SetListQuery(True, New mDB.Query With {.Query = e.CommandArgument})
                Me.UpPEnquiry.Update()
                'Me.UpPElaborations.Update()
                'Me.Txtpost.Text &= " " & e.CommandArgument

            Case "VIEW_POST"

                SetListPostUsersQuery(e.CommandArgument)

        End Select

    End Sub

#End Region

#Region "POST / USER"

    Public Sub SetListPostUsersQuery(key As String)
        Dim MaxPost = 100


        Dim results As New List(Of SimilText.MatchResult)
        Dim qs = CurrUser.View_Query(FolderParentId).SetSelect("query.*").ToList
        For Each q In qs

            Dim AD = mDB.Archive_Simil_Text.GetArchive(mDB.Archive_Simil_Text.ArchiveType.POST_QUERY, q.Id).GetSimilTextArchiveData
            Dim f As New SimilText.FindSimilarText(AD)

            f.Text = key
            f.RankMin = 1
            f.Find()
            f.Close()

            results.AddRange(f.Result.Matches.Take(2000).ToList)

        Next

        'id post
        Dim ids = (From r In results Order By r.Accuracy Descending Select New mDB._Query_Post With {.Id = r.Id, .Query_Id = r.Attribute0} Take 2000).ToList
        Dim AccCodes As New List(Of String)

        Dim dtPost As Object = Nothing
        Dim dtUser As Object = Nothing
        If ids.Count > 0 Then

            '--------------------------------
            'POST
            Dim posts = mDB._Query_Post.FillPost(ids, qs)

            'ATTENZIONE ORDINA PER ACCURACY E DATA

            Dim PostRes = (
                From r In results
                Join p In posts On p.Id Equals r.Id
                Select post = p, result = r
                Order By result.Accuracy Descending, post.Pubb_Date Descending
            Take MaxPost).ToList

            dtPost = PostRes

            ' CHART

            Dim DataChart As New List(Of Object())
            DataChart.Add({"data", "Post"})
            Dim currDate = Now.AddDays(-6).Date
            For ct = 0 To 6
                DataChart.Add({MyUI.Print.DateMonthDay(currDate), results.Where(Function(o) Utils.Conv.ToTimeStampDate(o.Attribute1).Date = currDate).Count})
                currDate = currDate.AddDays(1)

                'DataChart.Add({MyUI.Print.DateTimeShort(currDate), posts.Where(Function(o) round6(o.Pubb_Date) = currDate).Count})
                'currDate = currDate.AddHours(6)

                'DataChart.Add({MyUI.Print.DateTimeShort(currDate), posts.Where(Function(o) round1(o.Pubb_Date) = currDate).Count})
                'currDate = currDate.AddHours(1)

            Next

            Dim json = MyApp.JSONSerialize(New With {
                .data = DataChart
            })

            Me.AddJScript(SF("DrawChartFollower({0});", json))

            DataChart = New List(Of Object())
            DataChart.Add({"data", "Impression"})
            currDate = Now.AddDays(-6).Date
            For ct = 0 To 6
                'DataChart.Add({MyUI.Print.DateMonthDay(currDate), results.Where(Function(o) Utils.Conv.ToTimeStampDate(o.Attribute1).Date = currDate).Count})
                DataChart.Add({MyUI.Print.DateMonthDay(currDate), posts.Where(Function(o) o.Pubb_Date.Date = currDate).Sum(Function(o) o.Account_Follower_Count)})
                currDate = currDate.AddDays(1)
            Next

            json = MyApp.JSONSerialize(New With {
                .data = DataChart
            })

            Me.AddJScript(SF("DrawChartPostSend({0});", json))

            '--------------------------------
            'ACCOUNT

            AccCodes = posts.Select(Function(o) o.Account_Code).Distinct.ToList

            Dim AccuracyAccount = 1
            Dim AccFind = (
                From p In PostRes
                Group p By p.post.Account_Code, p.post.Account_Username Into g = Group
                Select
                    Account_Code, Account_Username,
                    Account_Follower_Count = g.First.post.Account_Follower_Count,
                    AccTot = g.Sum(Function(o) o.result.Accuracy),
                    post_count = g.Count
                Where AccTot >= AccuracyAccount Order By AccTot Descending
            Take MaxPost).ToList

            dtUser = AccFind

        End If

        '--------------------------------------------------
        ' LAYOUT
        '--------------------------------------------------

        Dim DataBind = UI.ListData.Bind(Me.ListHashtagPost, dtPost, {})
        DataBind = UI.ListData.Bind(Me.ListHashtagUser, dtUser)

        Me.LblPostFilter.Text = key & " (" & dtPost.count & ")"
        Me.LblUserFilter.Text = key & " (" & dtUser.count & ")"

        Me.UpPPostUserResult.Update()

    End Sub
    Public Function round6(d As Date) As Date

        Return New Date(d.Year, d.Month, d.Day, Math.Floor(d.Hour / 6) * 6, 0, 0)

    End Function
    Public Function round1(d As Date) As Date

        Return New Date(d.Year, d.Month, d.Day, d.Hour, 0, 0)

    End Function
    Protected Sub GridPosts_RowCommand(sender As Object, e As System.Web.UI.WebControls.GridViewCommandEventArgs) Handles GridPosts.RowCommand
        Dim g As GridView = sender
        Dim gr = UI.GridRow.GetRow(e.CommandSource)
        Dim butt = UI.GridRow.GetButton(gr, "BtnFollow")
        Dim AccountCode = butt.CommandArgument
        Dim tc = New WebApi.Twitter.TwitterClient(CurrAccount.GetOauth)



        Select Case e.CommandName
            Case "FOLLOW"

                tc.PostFriendshipsCreate("", AccountCode)
                CurrAccount.AddAccountLink(mDB._Account_Link.Type.FRIENDS, AccountCode, MyApp.Network.AccType.TWITTER_ACCOUNT)
                'controllatutto(butt.CommandArgument, e.CommandName)

            Case "UNFOLLOW"

                tc.PostFriendshipsDestroy("", AccountCode)
                CurrAccount.RemoveAccountLink(mDB._Account_Link.Type.FRIENDS, AccountCode)
                'controllatutto(butt.CommandArgument, e.CommandName)

        End Select


    End Sub

#End Region


    'Public Sub SetDataSearch(q As mDB.Query)

    '    Dim AD = mDB.Archive_Simil_Text.GetArchive(mDB.Archive_Simil_Text.ArchiveType.POST_QUERY, q.Id).GetSimilTextArchiveData

    '    dic = AD.Dictionary


    '    Dim f As New SimilText.FindSimilarText(AD)

    '    f.Text = ""
    '    f.RankMin = 0
    '    f.Find()
    '    f.Close()


    '    Me.LblExec.Text = String.Format("Analisi effettuata in {0} sec.", f.Result.ExecTime)

    '    '----------------------------------------------------------
    '    'trova le parole + utilizzate
    '    'Dim wids As New Dictionary(Of UInteger, Integer)
    '    'For Each r In f.Result.Matches
    '    '    For ct = 0 To r.Seq.Length - 1

    '    '        If wids.ContainsKey(r.Seq(ct)) Then
    '    '            wids(r.Seq(ct)) += 1
    '    '        Else
    '    '            wids.Add(r.Seq(ct), 1)
    '    '        End If

    '    '    Next

    '    'Next
    '    Dim wids = f.Result.WordCluster1


    '    TotHashtag = wids.Sum(Function(o) o.Value)

    '    seq = New SimilText.TextTools(q.Query, AD).TextToNumber.ToDictionary(Of UInteger)(Function(o) o)

    '    Dim hash_ids = wids.Where(Function(o) AD.Dictionary.WordsList(o.Key).IsHashtag).OrderByDescending(Function(o) o.Value).Take(100).ToList
    '    Dim word_ids = wids.Where(Function(o) Not AD.Dictionary.WordsList(o.Key).IsHashtag).OrderByDescending(Function(o) o.Value).Take(100).ToList
    '    'Dim lwids = wids.Where(Function(o) f.TI.Dictionary.WordsList(o.Key).IsHashtag).OrderByDescending(Function(o) o.Value).Take(100).ToList
    '    TotCloudHashtag = hash_ids.Sum(Function(o) o.Value)
    '    TotCloudword = word_ids.Sum(Function(o) o.Value)

    '    Me.RptHasttag.DataSource = hash_ids
    '    Me.RptHasttag.DataBind()

    '    Me.RptWord.DataSource = word_ids
    '    Me.RptWord.DataBind()



    '    '----------------------------------------------------------
    '    ' trova i cluster
    '    Clusters = New Dictionary(Of String, Integer)
    '    'For Each r In f.Result.Matches
    '    '    Clustered(r.Seq, 2)
    '    'Next

    '    Dim clus_ord2 = Clusters.OrderByDescending(Function(o) o.Value).Take(20).ToList

    '    Me.RptCluster2.DataSource = clus_ord2
    '    Me.RptCluster2.DataBind()


    '    Clusters = New Dictionary(Of String, Integer)
    '    'For Each r In f.Result.Matches
    '    '    Clustered(r.Seq, 3)
    '    'Next

    '    Dim clus_ord3 = Clusters.OrderByDescending(Function(o) o.Value).Take(20).ToList

    '    Me.RptCluster3.DataSource = clus_ord3
    '    Me.RptCluster3.DataBind()

    '    '----------------------------------------------------------
    '    ' images


    '    'Dim DtImage = q.Tab_QueryPost.
    '    '    Where("image_url", "<>", "").
    '    '    OrderBy("share desc", "tot_foll desc").
    '    '    GroupBy("image_url").
    '    '    SetSelect("image_url", "sum(account_follower_count) as tot_foll", "if(share_count > 0 ,1 ,0) as share").
    '    '    Limit(24).
    '    'ToDataTable()

    '    Dim DtImage = q.Tab_QueryPost.
    '        Where("image_url", "<>", "").
    '        OrderBy("share_count desc", "account_follower_count desc").
    '        GroupBy("image_url").
    '        SetSelect("image_url").
    '        Limit(24).
    '    ToDataTable()


    '    Me.RptImages.DataSource = DtImage
    '    Me.RptImages.DataBind()


    'End Sub



    Protected Sub BtnSugg_Click(sender As Object, e As EventArgs) Handles BtnSugg.Click


        Dim tw = New WebApi.Twitter.TwitterClient(CurrAccount.GetOauth)

        Dim dt = tw.GetSuggestions("it")

        'Dim dt = tw.GetUsersSuggestion("business", "")

        UI.Rep.Bind(Me.RptSugg, dt)

    End Sub

    Protected Sub BtnUserSugg_Click(sender As Object, e As EventArgs) Handles BtnUserSugg.Click

        Dim tw = New WebApi.Twitter.TwitterClient(CurrAccount.GetOauth)

        Dim dt = tw.GetUsersSuggestion(Me.TxtSlug.Text, "it")

        'Dim dt = tw.GetUsersSuggestion("business", "")

        UI.Rep.Bind(Me.RptUsers, dt.users)

    End Sub


End Class
